package co.edu.unal.geditor.view.tools;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;

import co.edu.unal.geditor.controller.App;
import co.edu.unal.geditor.controller.action.tool.SelectionToolAction;
import co.edu.unal.geditor.model.BoundBox;
import co.edu.unal.geditor.model.RectangleElement;
import co.edu.unal.geditor.view.Canvas;

public class SelectionTool extends Tool {
	// v0.6 : SelectionTool provides its own Factory class
	private static class Factory extends ToolFactory {
		protected Tool create() {
			return new SelectionTool();
		}
	}

	// this block executed when the class object is loaded in the VM
	// registers its Factory
	static {
		ToolFactory.register(SelectionTool.class.getName(), new Factory());
	}

	@Override
	protected void initAction() {
		setAction(new SelectionToolAction());
		if (feedbackGraphElemet == null) {
			feedbackGraphElemet = new RectangleElement(new Point(0, 0),
					new Point(20, 20));
		}

	}

	@Override
	public void processMousePressed( Point ptPressed )
	{
		m_ptPressed = ptPressed;
		m_ptCurrent = ptPressed;
		if (ActiveAction==MOVE){
			App.getInstance().getDrawing().elementMoved(App.getInstance().getCanvas().getActiveFeedbackGraphElement());
		}
		if (ActiveAction==RESIZE){
			App.getInstance().getDrawing().elementResized(App.getInstance().getCanvas().getActiveFeedbackGraphElement());
		}
			
	}

	@Override
	public void processMouseDragged( Point pt )
	{
		Canvas canvas = App.getInstance().getCanvas();
	
		Graphics2D g = (Graphics2D)canvas.getGraphics();
		g.setColor( Color.LIGHT_GRAY );
		g.setXORMode( Color.WHITE );
		g.setStroke( m_dashStroke );
		
		
		if (ActiveAction==SELECT) 
		{
			drawFeedback( g );
			m_ptCurrent = pt;
			drawFeedback( g );		
		}
		if (ActiveAction==MOVE)
		{
			int x = pt.x-m_ptPressed.x;
			int y = pt.y-m_ptPressed.y;
			m_ptPressed=pt;
			App.getInstance().getCanvas().getActiveFeedbackGraphElement().getBoundBox().getView().moved(x, y);
			
			App.getInstance().getCanvas().update();
		}
		if (ActiveAction==RESIZE)
		{
			App.getInstance().getCanvas().getActiveFeedbackGraphElement().getBoundBox().getView().resizing(pt);
			
			App.getInstance().getCanvas().update();
		}
		
	
	}

	@Override
	public void processMouseReleased(Point ptReleased) {

		if (ActiveAction == SELECT) {
			BoundBox bb = new BoundBox(m_ptPressed, ptReleased);

			App.getInstance().getDrawing().select(bb);
			App.getInstance().getCanvas().update();
		}
	}

	@Override
	public void processMouseMoved(Point ptActualPos) {
	
		App.getInstance().getDrawing().mouseMoving(ptActualPos);
	}


}
